package com.jerry.provider.controller;

import com.jerry.common.bean.Ad;
import com.jerry.common.feign.AdFeignClient;
import com.jerry.provider.service.AdService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class AdController implements AdFeignClient {
	
	@Autowired
	private AdService adService;
	@Autowired
	private DiscoveryClient client;

	@Override
	public List<Ad> list() {
		ServiceInstance instance = client.getLocalServiceInstance();
		List<Ad> adList = adService.list();
		for (Ad ad : adList) {
			ad.setHost(instance.getHost());
			ad.setPort(instance.getPort());
			ad.setServerId(instance.getServiceId());
			System.out.println("provider === AD === "+ad);
		}
		return adList;
	}

	@Override
	public Ad get(@PathVariable("id") Long id) {
		ServiceInstance instance = client.getLocalServiceInstance();
		Ad ad = adService.get(id);
		ad.setHost(instance.getHost());
		ad.setPort(instance.getPort());
		ad.setServerId(instance.getServiceId());
		System.out.println("provider === AD === "+ad);
		return ad;
	}

	@Override
	public boolean add(@RequestBody Ad ad) {
		return adService.add(ad);
	}

	@Override
	public boolean update(@RequestBody Ad ad) {
		return adService.update(ad);
	}

	@Override
	public void delete(@PathVariable("id") Long id) {
		adService.delete(id);
	}

}
